<template>
  <div class="layout-all">
    <control :config="config" />
    <div class="layout-header" style="float:left" v-if="model=='shop'">
        <el-checkbox v-model="update_checked" @change="change_update" label="实时更新" border></el-checkbox>
    </div>
    <div class="layout-content">
      <el-table
        ref='table_order'
        v-loading="loading"
        :data="tableData"
        @expand-change="select_click"
        stripe
        align="center"
        highlight-current-row
        height="800"
        style="width: 100%;margin-top:50px"
      >
        <el-table-column
          label="订单商品"
          align="center"
          type="expand"
          width="80"
        >
          <template slot-scope="scope">
            <orderGoodsList :checked="checked" :order_goods="scope.row.order_goods" @handleSelectionChange="handleSelectionChange" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="create_time" label="下单日期" minWidth="120" >
            <template slot-scope="scope" >
              <div class="flex_row">
              <div>{{scope.row.create_time}}</div>
              <div v-if="scope.row.is_new!=undefined" style="color:#ff0000">新</div>
              </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="sn" label="订单号" minWidth="90" />
        <el-table-column align="center" prop="shop_title" label="店铺" width="120" v-if="model=='admin'"/>
        <el-table-column align="center" prop="status" label="订单状态" width="120">
          <template class="down" slot-scope="scope">
            <el-tag  :type="status_array[scope.row.status]" disable-transitions>{{scope.row.status_str}}</el-tag>
            <div class="shen-he" v-if="scope.row.type>1">{{type_arr[scope.row.type]}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="dining_id" label="用餐方式" width="80" v-if="pro_type==2">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.dining_id !='' ? 'success' : 'warning'"
              disable-transitions
            >{{ scope.row.dining_id !='' ? scope.row.dining_id : "外卖" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="total_amount" label="订单金额" width="100" />
        <el-table-column align="center" prop="balance_money" label="使用余额" width="100" />
        <el-table-column align="center" prop="integral_money" label="使用积分" width="100" />
        <el-table-column align="center" prop="is_pay" label="在线支付" width="80">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.is_pay === 1 ? 'success' : 'warning'"
              disable-transitions
            >{{ scope.row.is_pay === 1 ? "是" : "否" }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="can_refund_amount" label="退款金额" width="150" /> -->
        <el-table-column align="center" prop="refund_status" label="退款状态" width="100" >
          <template slot-scope="scope">
            <el-tag
              :type="status_array[scope.row.refund_status]"
              disable-transitions>{{scope.row.refund_status_str}}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="postage" label="运费" width="80"/> -->
        <el-table-column align="center" prop="user.account" label="用户"/>
        <el-table-column align="center" prop="leader_name" label="收货人" width="80" />
        <el-table-column align="center" prop="user_tel" label="收货人电话" width="120" />
        <el-table-column align="center" prop="leader_full_address" label="用户地址" minWidth="100" />
        

        <el-table-column
          v-if="user_id==undefined"
          align="center"
          prop="telephone"
          width="340"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="success"
              v-if="model=='shop'&&scope.row.status==0&&is_open_paycode>0"
              @click="pay_order(scope.row.id)"
            >已支付
            </el-button>
             <router-link :to="(model=='shop'?'./form/':'./order_form/') + scope.row.id">
            <el-button size="small" type="info" >详情 </el-button>
             </router-link>
            <el-button
              size="small"
              type="primary"
              :disabled="scope.row.status<2||scope.row.status>3"
              @click="lookwl(scope.row.id)"
            >物流
            </el-button>
            <el-button size="small" v-if="model=='shop'" :disabled="scope.row.is_delivery_btn==0" type="success" @click="send_isshow(scope.row)">发货 </el-button>
            <el-button size="small" v-if="scope.row.shop_is_refund_btn>0&&model=='shop'" type="warning" :disabled="scope.row.status==0" @click="refund_isshow(scope.row)">退款 </el-button>
            <!-- <el-button
              type="danger"
              icon="el-icon-delete"
              @click="onDel(scope.row.id)"
            /> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      :current-page="current_page"
      :page-size="per_page"
      layout="total, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 发货 -->
    <el-dialog title="发货信息" :visible.sync="send_dialogVisible" :width="isMobile()?'100%':'30%'">
        <send-dig-delivery @closeDelivery="closeDelivery" :send_goods="send_goods" :select_row="select_row" :print="print" :send_options="send_options"/>
    </el-dialog>
    <!-- 退款 -->
    <el-dialog
      title="退款信息"
      :visible.sync="refund_dialogVisible"
      :width="isMobile()?'100%':'30%'"
    >
      <el-form
        ref="refund_form"
        :model="refund_goods"
        label-width="120px"
      >
      <el-form-item v-if="refund_goods.status==1" label="快递单号(收到后请退款):" prop="is_refund">
        <el-input v-model="refund_goods.express_sn" placeholder="快递单号"></el-input>
        </el-form-item>
      <el-form-item v-if="refund_goods.status==2" label="商品已发货:" prop="is_refund">
          <el-radio-group v-model="refund_goods.is_refund_agree">
            <el-radio :label="0">拒绝退货</el-radio>
            <el-tooltip class="item" effect="dark" content="同意买家退货,收到货后再退款" placement="top-start">
            <el-radio :label="1">先退货后退款</el-radio>
            </el-tooltip>
            <el-radio :label="2">直接退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否退款:" prop="is_refund">
          <el-radio-group v-model="refund_goods.is_refund">
            <el-radio :disabled="refund_goods.status==2"  :label="0">否</el-radio>
            <el-radio :disabled="refund_goods.status==2"  :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="refund_goods.is_refund==0" label="拒绝退款原因:" prop="refund_refuse_note">
          <el-input
            v-model="refund_goods.refund_reply"
            type="textarea"
            :rows="5"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="refund_dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onRefund">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 物流信息 -->
    <el-dialog title="物流信息" :visible.sync="logistics_isshow" :width="isMobile()?'50%':'30%'">
      <el-timeline >
        <div v-for="(item,i) in express_list" :key="item.goods_list.id">
          <div v-for="(goods, index) in item.goods_list">
            <el-tag>{{goods.express_name}}</el-tag>
            <el-tag type="success">{{goods.express_sn}}</el-tag>
            <el-tag type="warning" style="margin-bottom: 10px;">{{goods.goods_title}}</el-tag>
            <el-tag type="success">{{goods.spec_key_name}}</el-tag>
          </div>
          <el-timeline-item
            v-for="(activity, index) in item.express_info.list"
            :key="index"
            :icon="index==0||index==item.express_info.list.length-1?'el-icon-more':''"
            type="primary"
            :color="index==0||index==item.express_info.list.length-1?'':'#0bbd87'"
            size="large"
            :timestamp="activity.AcceptTime"
          >
            {{ activity.AcceptStation }}
          </el-timeline-item>
        </div>
      </el-timeline>
      <span slot="footer" class="dialog-footer">
        <el-button @click="logistics_isshow = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import control from '../control/control'
import sendDigDelivery from './sendDigDelivery'
import orderGoodsList from './orderGoodsList'
import axios from 'axios'
import {
  getToken
} from '@/utils/auth'
export default {
  props:['model','user_id','region_id'],
  name:'orderList',
  components: { control ,sendDigDelivery,orderGoodsList},
  data() {
    return {
      loading: true,
      loadinged: false,
      select_row:[],
      type_arr:['','','特','秒','团'],
      pro_type:0,
      express_list:[],
      status_array:['warning','info','primary','success','danger','primary',''],
      activities: [
        {
          AcceptStation: '深圳------已经发往站点',
          AcceptTime: '2020-07-02 20:46',
          size: 'large',
          type: 'primary',
          icon: 'el-icon-more'
        },
      ],
      update_checked: false,
      is_button: false,
      checked: 0,
      update_time: '',
      send_dialogVisible: false,
      refund_dialogVisible: false,
      logistics_isshow: false,
      config: [
        { type: 'text', placeholder: '请输入订单号', field: 'sn', val: '' },
        { type: 'text', placeholder: '用户名', field: 'user', val: '' },
        {
          type: 'select',
          placeholder: '订单状态',
          field: 'status',
          val: '',
          options: [
            { value: 0, label: '未支付' },
            { value: 1, label: '待发货' },
            { value: 2, label: '已发货' },
            { value: 3, label: '已完成' },
            { value: 4, label: '已取消' },
            { value: 6, label: '有退款' }
          ]
        },
        {
          type: 'select',
          placeholder: '配送方式',
          field: 'delivery',
          val: '',
          options: [
            { value: 1, label: '快递公司' },
            { value: 2, label: '自提' },
            { value: 3, label: '线下配送' },
          ]
        },
        {
          type: 'select',
          placeholder: '类型',
          field: 'type',
          val: '',
          options: [
            { value: 1, label: '普通订单' },
            { value: 2, label: '特价订单' },
            { value: 3, label: '秒杀订单' },
            { value: 4, label: '团购订单' },
          ]
        },
        {
          type: 'date_time',
          placeholder: '请选择订单状态',
          field: 'date_time',
          val: '',

        },
        {
          type: 'output',
          button_name: '导出',
          class: 'primary',
          icon: 'el-icon-download',

        }
      ],
      searchWhere: {
        sn: ''
      },
      sn: '',
      interval: '',
      send_goods: {
        order_goods_id: [],
        goods_id: [],
        express_id: 0,
        express_sn: '',
        remark: '',
        express_name: '',
        goods_name: '商品'
      },
      send_options: [],
      audio: [],
      refund_goods: {
        order_goods_id: [],
        is_refund: 0,
        is_refund_agree: 0,
        refund_refuse_note: ''
      },
      print: [],
      tableData: [],
      total: 0,
      is_open_paycode: 0,
      current_page: 1,
      per_page: 14,
      refund_rules: {
        refund_refuse_note: [
          { required: true, message: '请输入退款原因', trigger: 'blur' }
        ]
      }
    }
  },
  activated(){
    if(this.$getUpdate()){
      this.onSearch()
    }
  },
  created() {
    if(this.user_id!=undefined){
      this.searchWhere.user_id=this.user_id
    }
    this.onSearch()
    this.get_express_code()
    this.audio = new Audio()
    this.audio.src =this.get_upload_url()+ "static/mp3/snatchforbills.mp3"
  },
  destroyed(){
    clearInterval(this.interval)
    this.interval=''
  },
  methods: {
    closeDelivery(up){
       this.send_dialogVisible = false
       console.log(this.send_dialogVisible)
       if(up)
        this.onSearch()
    },
    init_update(){
      const that=this
      that.interval=setInterval(function(){
        if(that.current_page==1){
          console.log(4444)
          that.up_date()
        }
      },8000)
    },
    change_update(e){
      const that=this
      if(!this.update_checked){
        clearInterval(this.interval)
        this.interval=''
      }else if(this.interval==''){
        this.init_update()
      }
      localStorage.setItem("auto_update", e?"1":"0");
      
    },
    // 查询
    handleSizeChange(val) {
      this.onSearch()
    },
    lookwl(id){
      this.get('/'+this.model+'/Order/express_info', {order_id:id}, 'POST').then(e => {
        this.express_list=e.express_list
        this.logistics_isshow = true
      })
    },
    onOutput(){
      this.$msg_confirm_show("确定要导出订单吗?").then((e) => {
        let form={}
        form.map = this.searchWhere
        let url=this.get_upload_url()+this.model+'/Order/output_excel'
        axios.post(url, form, {
          responseType: 'blob',
          timeout: 10000 ,
          headers :{
          passport:getToken()
        }
        },

        ).then((res) => {
          console.log('res', res);
          const blob = res.data;
          const reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = (e) => {
            const a = document.createElement('a');

            const disposition = res.headers['content-disposition'];
            if(disposition!=undefined){
              let fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length);
              // iso8859-1的字符转换成中文
              fileName = decodeURI(escape(fileName));
              // 去掉双引号
              fileName = fileName.replace(/\"/g, "");
              a.download = fileName;
              // 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"20181211191944.zip\"",
              a.href = e.target.result;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
            }else{
              const Base64 = require('js-base64').Base64
              console.log(e.target.result)
              let text=e.target.result.substring(e.target.result.indexOf(','))
              const exStr = Base64.decode(text)
              let jsonData = JSON.parse(exStr)
              //this.$msg_confirm_show(jsonData.msg).then((e) => {})
              this.$message(jsonData.msg)


            }

          };
        }).catch((err) => {
          console.log(err.message);
        });
      });
    },
    handleSelectionChange(val) {
      // 发货参数
      this.send_goods = {
        order_goods_id: [],
        express_id: 0,
        express_sn: '',
        remark: '',
        goods_name: '商品',
        express_name: ''
      }
      if (val.length >0) {
        this.send_goods.express_id = val[0].express_id==0?'':val[0].express_id
         if(val[0].express_name=="自提"){
          this.send_goods.express_sn ="自提"
          this.send_goods.express_id =0
        }
        if (val.length === 1) {
          this.send_goods.order_goods_id = [val[0].id]
        } else {
          val.forEach(v => {
            this.send_goods.order_goods_id.push(v.id)
          })
        }
      }
      // 退款参数
      this.refund_goods = {
        order_goods_id: [],
        is_refund: 0,
        is_refund_agree: 0,
        refund_refuse_note: ''
      }
      if (val.length ==0) {
      }else if (val.length === 1) {
        this.refund_goods.order_goods_id = [val[0].id]
      } else {
        val.forEach(v => {
          this.refund_goods.order_goods_id.push(v.id)
        })
      }
    },
    handleCurrentChange(val) {
      this.current_page = val
      this.onSearch()
    },
    up_date(){
      this.get('/'+this.model+'/Order/auto', {update_time:this.update_time}, 'POST').then(e => {
        if(e.list.data.length>0){
          for(let i in e.list.data){
            e.list.data[i].is_new=1
            for(let j in this.tableData){
              if(this.tableData[j].id==e.list.data[i].id){
                this.tableData.splice(j, 1)
                break
              }
            }
            this.tableData.unshift(e.list.data[i])
          }
          this.update_time=e.list.data[e.list.data.length-1].update_time
          this.audio.play()
        }
      })
    },
    onSearch() {
      this.loading = true
      const form = {}
      form.page = this.current_page
      form.map = this.searchWhere
      form.map.region_id = this.region_id
      this.current_page = 1
      this.get('/'+this.model+'/Order/index', form, 'POST').then(e => {
        this.tableData = e.list.data
        this.is_open_paycode = e.is_open_paycode
        this.pro_type = e.pro_type
        this.per_page = e.list.per_page
        this.total = e.list.total
        this.current_page = e.list.current_page
        this.loading = false
        this.print = e.print

        if(this.tableData.length>0){
          this.update_time=this.tableData[0].update_time
        }

        if(this.update_checked&&this.interval==''){
          this.init_update()
        }
        if(this.model=='admin'&&!this.loadinged){
          this.loadinged=true
          e.shop_list.unshift({value: '', label: '全部店铺' })
          this.config.splice(this.config.length-1,0,{
          type: 'select',
          placeholder: '店铺',
          field: 'shop_id',
          val: '',
          options: e.shop_list
        },)
        }
      })
    },
    pay_order(id){
      this.$msg_confirm_show("此单设置为已支付?").then((e) => {
        this.get('/'+this.model+'/Order/pay_order', {order_id:id}, 'POST').then(e => {
          this.onSearch()
        })
      })
    },
    // 添加
    onAdd() {},
    // 编辑
    onEdit(id) {
      let mapList={map:this.searchWhere,current_page:this.current_page}
      localStorage.setItem(process.env.CACHE_CONTROL,JSON.stringify(mapList))
      this.$router.push('./form?id='+id);
    },
    // 删除
    onDel(id) {
      this.$msg_confirm().then(e => {
        if (e) {
          this.get('/'+this.model+'/Order/del?id=' + id, this.form, 'POST').then(e => {
            this.onSearch()
          })
        }
      })
    },
    // rowClassName({row, rowIndex}) {
    //     //把每一行的索引放进row
    //     row.index = rowIndex;
    //   },
    select_click(row,b){
      if(b.length>0){
        if(b.length>1){
          for(let i=0;i<b.length-1;i++){
            this.$refs.table_order.toggleRowExpansion(b[i],false)
          }
        }
        //if(row.index!=undefined)
        this.select_row=row
        if(row.is_new!=undefined){
          row.is_new=undefined
          console.log(b)
        }
      }else{
        this.select_row=[]
      }
      this.refund_goods.order_goods_id=[]
    },
    // 发货判断
    send_isshow(row) {
      if(this.is_button)return
      this.is_button=true
      if(this.select_row!=[]&&this.select_row.id!=row.id){
        this.refund_goods.order_goods_id=[]
        this.$refs.table_order.toggleRowExpansion(this.select_row,false)
        this.select_row=[]
      }
      
      if (this.refund_goods.order_goods_id.length==0) {
        // this.$message.error('请选择一个商品')
        const $table = this.$refs.table_order
        $table.toggleRowExpansion(row,true)
        setTimeout(()=>{
          this.checked++
          this.is_button=false
          this.send_dialogVisible=true
        },500)
        return false
      }
      this.is_button=false
      this.send_dialogVisible = true
    },

    // 退款判断
    refund_isshow(row) {
      console.log(row)
      if(this.is_button)return
      
      this.is_button=true

      if(this.select_row!=[]&&this.select_row.id!=row.id){
        this.refund_goods.order_goods_id=[]
        this.$refs.table_order.toggleRowExpansion(this.select_row,false)
        this.select_row=[]
      }

      if (this.refund_goods.order_goods_id.length==0) {
        // this.$message.error('请选择一个商品')
        const $table = this.$refs.table_order
        $table.toggleRowExpansion(row,true)
        setTimeout(()=>{
          this.checked++
          setTimeout(()=>{
            this.is_button=false
            if(row.status==2&&row.refund_status==3)
              this.refund_goods.status=row.status
            else if(row.status==2&&row.refund_status>=4){
              this.refund_goods.status=1
              this.refund_goods.express_sn=row.order_goods[0].order_refund_logs[0].express_sn
            }else this.refund_goods.status=0

            this.refund_dialogVisible=true
          },100)
        },500)
        return false
      }
      if(row.status==2&&row.refund_status==3)
        this.refund_goods.status=row.status
      else if(row.status==2&&row.refund_status>=4){
        this.refund_goods.status=1
        this.refund_goods.express_sn=row.order_goods[0].order_refund_logs[0].express_sn
      }else this.refund_goods.status=0
      this.is_button=false
      this.refund_dialogVisible = true
    },
    // 退款
    onRefund(row) {
      this.$refs['refund_form'].validate(valid => {
        console.log(this.refund_goods)
        this.get('/'+this.model+'/Order/refund', this.refund_goods, 'POST').then(e => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.refund_dialogVisible = false
          this.onSearch()
        })
      })
    },
    // 获取快递公司编码
    get_express_code() {
      this.get('/shop/OrderGoods/express_code', name, 'POST').then(e => {
        this.send_options = e.list
      })
    }
    // 物流信息
  }
}
</script>

<style>
.layout-all {
  margin-top: 20px;
  margin-left: 10px;
}
.layout-content {
  margin-top: 20px;
}
.el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  .flex_row {
  display: flex;
  align-items: center;
}
.down{
  position: relative;
}
.shen-he {
    position: absolute;
    right: 4px;
    top: 13px;
    font-size: 14px;
    z-index: 10;
    border-radius: 100%;
    height: 25px;
    line-height: 17px;
    text-align: center;
    background-color: rgb(255 0 0 / 68%);
    color: rgb(255, 255, 255);
    padding: 5px;
}
</style>>
